package com.sise.wangzhan.client;

import com.netflix.config.ConfigurationManager;
import com.netflix.hystrix.HystrixCommandMetrics;
import com.sise.wangzhan.command.MyCommand;
import com.sise.wangzhan.command.SecondCommand;

/**
 * @Classname SecondCommandClient
 * @Description TODO
 * @Date 2020/4/29 19:50
 * @Created by wangzhan
 */
public class SecondCommandClient {
    public static void main(String[] args) throws InterruptedException {
        //10秒内有5个请求，满足第一个断路器开启条件
        ConfigurationManager.getConfigInstance().setProperty(
                "hystrix.command.default.metrics.rollingStats.timeInMilliseconds",10000
        );
        ConfigurationManager.getConfigInstance().setProperty(
                "hystrix.command.default.circuitBreaker.requestVolumeThreshold",5
        );
        // 请求的错误率超过50%  ,满足第二个断路器开启条件
        ConfigurationManager.getConfigInstance().setProperty(
                "hystrix.command.default.circuitBreaker.errorThresholdPercentage",50
        );
        //设置休眠期， 断路器开启后，进入到不再执行命令的休眠期，默认值为5秒，此设置为1秒
        ConfigurationManager.getConfigInstance().setProperty(
                "hystrix.command.default.circuitBreaker.sleepWindowInMilliseconds",1000
        );

        boolean isTimeout = true;

        for (int i = 1; i <= 15; i++) {
            //选好执行15次命令请求
            SecondCommand secondCommand = new SecondCommand(isTimeout);
            secondCommand.execute();

            //输出健康状态等信息
            HystrixCommandMetrics.HealthCounts hc = secondCommand.getMetrics().getHealthCounts();
            System.out.println("断路器状态："+secondCommand.isCircuitBreakerOpen()+
                    ",请求总数：" + hc.getTotalRequests());
            //断路器是否开启
            if (secondCommand.isCircuitBreakerOpen()){
                //关闭断路器
                isTimeout = false;
                System.out.println("========断路器被开启,等待休眠期结束========");
                // **休眠期会在1秒后结束，此处等待2秒，确保休眠期结束**
                Thread.sleep(2000);
            }
        }

    }
}
